package com.houweishi.module.staff.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.houweishi.common.annotation.Excel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.houweishi.common.annotation.Log;
import com.houweishi.common.core.controller.BaseController;
import com.houweishi.common.core.domain.AjaxResult;
import com.houweishi.common.enums.BusinessType;
import com.houweishi.module.staff.domain.BizStaff;
import com.houweishi.module.staff.service.IBizStaffService;
import com.houweishi.common.utils.poi.ExcelUtil;
import com.houweishi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 员工管理Controller
 * 
 * @author houweishi
 * @date 2023-02-21
 */
@RestController
@RequestMapping("/module/staff")
public class BizStaffController extends BaseController
{
    @Autowired
    private IBizStaffService bizStaffService;

    /**
     * 查询员工管理列表
     */
    @PreAuthorize("@ss.hasPermi('module:staff:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizStaff bizStaff)
    {
        startPage();
        List<BizStaff> list = bizStaffService.selectBizStaffList(bizStaff);
        return getDataTable(list);
    }

    /**
     * 导出员工管理列表
     */
    @PreAuthorize("@ss.hasPermi('module:staff:export')")
    @Log(title = "员工管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizStaff bizStaff)
    {
        List<BizStaff> list = bizStaffService.selectBizStaffList(bizStaff);
        ExcelUtil<BizStaff> util = new ExcelUtil<BizStaff>(BizStaff.class);
        util.exportExcel(response, list, "员工管理数据");
    }


    /**
     * 导入模板下载
     */
    //    @RequiresPermissions("system:student:view")
    //    @PreAuthorize("@ss.hasPermi('module:customer:view')")
    @PostMapping("/importTemplate")
    //    @ResponseBody
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<BizStaff> util = new ExcelUtil<BizStaff>(BizStaff.class);
        util.importTemplateExcel(response,"员工信息数据");
    }

    /**
     * 批量导入员工信息数据
     */
    //    @RequiresPermissions("system:customer:import")
    @Log(title = "导入员工", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('module:customer:import')")
    @PostMapping("/importCustomer")
    //    @ResponseBody
    public AjaxResult importCustomer(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<BizStaff> util = new ExcelUtil<BizStaff>(BizStaff.class);
        List<BizStaff> staffList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = bizStaffService.importStaff(staffList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * 获取员工管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('module:staff:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizStaffService.selectBizStaffById(id));
    }

    /**
     * 新增员工管理
     */
    @PreAuthorize("@ss.hasPermi('module:staff:add')")
    @Log(title = "员工管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizStaff bizStaff)
    {
        return toAjax(bizStaffService.insertBizStaff(bizStaff));
    }

    /**
     * 修改员工管理
     */
    @PreAuthorize("@ss.hasPermi('module:staff:edit')")
    @Log(title = "员工管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizStaff bizStaff)
    {
        return toAjax(bizStaffService.updateBizStaff(bizStaff));
    }

    /**
     * 删除员工管理
     */
    @PreAuthorize("@ss.hasPermi('module:staff:remove')")
    @Log(title = "员工管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(bizStaffService.deleteBizStaffByIds(ids));
    }

    /**
     * 修改员工在职状态管理（如果为入职则新增该员工与打卡类型绑定）,只传员工id和状态。
     */
    @PreAuthorize("@ss.hasPermi('module:staff:edit')")
    @Log(title = "员工管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestBody BizStaff bizStaff)
    {
        return toAjax(bizStaffService.updateBizStaffStatus(bizStaff));
    }


    /**
     * 自定义字段导出员工
     */
//    @PreAuthorize("@ss.hasPermi('module:copy:export2')")
    @Log(title = "自定义导出员工信息")
    @GetMapping("/get/export2")
    public void export3(HttpServletResponse response, BizStaff bizStaff) throws IllegalAccessException, IOException, ParseException {

        List<BizStaff> list = bizStaffService.selectBizStaffList(bizStaff);
        if(!CollectionUtils.isEmpty(list)){
            list.forEach(staff->{});
        }


        //创建HSSFWorkbook（excel文档对象）
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建sheet对象（excel表单）
        HSSFSheet sheet = wb.createSheet("员工");

        //字符串分割，并把String[]转换为list
        //        String[] fieldsNames = bizCopy.getFieldsNames().split(",");
        //        List<String> requestFields = Arrays.stream(fieldsNames).collect(Collectors.toList()) ;
        List<String> requestFields = StrUtil.split(bizStaff.getFieldsNames(),",");

        int startRow = 0;

        //表头
        HSSFRow rowHeader = sheet.createRow(startRow);
        Field[] fields = list.get(0).getClass().getDeclaredFields();
        for (int k = 0;k<requestFields.size();k++){
            String str = requestFields.get(k);
            Field field = Arrays.stream(fields).filter(x-> StrUtil.equals(x.getName(),str,true)).findFirst().get();
            HSSFCell cell3 = rowHeader.createCell(k);
            if(field.getAnnotation(Excel.class) != null){
                cell3.setCellValue(field.getAnnotation(Excel.class).name());
            }
        }
        for(BizStaff bizStaff1:list){
            startRow = startRow +1;
            //表内容
            HSSFRow rowContent = sheet.createRow(startRow);
            for(int k = 0;k<requestFields.size();k++){
                String str = requestFields.get(k);
                Field field = Arrays.stream(fields).filter(x-> StrUtil.equals(x.getName(),str,true)).findFirst().get();
                HSSFCell cell3 = rowContent.createCell(k);
                field.setAccessible(true);
                if(field.get(bizStaff1)!=null){
                    if(field.getAnnotation(JsonFormat.class) != null){
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                        Date date = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US).parse(field.get(bizStaff1).toString());
                        String formattedDate = formatter.format(date);
                        cell3.setCellValue(formattedDate);//时间格式转换
//                    }else if (field.getAnnotation(Excel.class).name().indexOf("性别")>=0){
                    }
                    else{ cell3.setCellValue(field.get(bizStaff1).toString());
                    }
                }
            }
        }
        String fileName = "员工";
        //输出excel文件
        OutputStream output = response.getOutputStream();
        //设置Header和contentType,避免报错
        response.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(fileName,"utf-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        wb.write(output);
        output.close();
    }

}
